package com.example.socketserver.socket;

import com.alibaba.fastjson2.JSON;
import com.example.socketserver.message.Message;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;

import javax.jws.WebService;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat/{username}")
@Component
public class WebServer  {

    public static final Map<String,Session> map=new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username")String username){
        boolean b = map.containsKey(username);
        if(b){
            System.out.println("用户："+username+" 重复登录");
            return;
//            throw new RuntimeException("用户："+username+" 重复登录");
        }else {
            System.out.println("用户："+username+" 登录成功");
            map.put(username,session);
        }
    }
    @OnClose
    public void onClose(Session session,@PathParam(value = "username")String username){
        System.out.println("用户："+username+" 退出登录");
        map.remove(username);
    }
    @OnError
    public void onError(Throwable throwable,@PathParam(value = "username")String username){
        System.out.println(throwable.getMessage());
    }
    @OnMessage
    public void onMessage(String msg,@PathParam(value = "username")String username){
//        System.out.println("用户："+username+" 发来消息："+msg);
        Message jsonObject = JSON.parseObject(msg, Message.class);
        Session session = map.get(jsonObject.getTo());
        String message=jsonObject.getMsg();
        send(jsonObject.getTo(),session,message);
    }
    private void send(String to,Session session,String message){
        if(session==null){
            System.out.println("用户："+to+" 不在线");
//            throw new RuntimeException("用户："+to+" 不在线");
            return;
        }
        session.getAsyncRemote().sendText(message);
    }
}
